package com.elvin.zoe;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.log4j.Logger;

import com.elvin.zoe.parser.Parser;
import com.elvin.zoe.parser.call.CallLogXmlParser;
import com.elvin.zoe.parser.im.MsnParser;
import com.elvin.zoe.parser.im.QqParser;
import com.elvin.zoe.parser.jiayuan.JiayuanParser;
import com.elvin.zoe.parser.sms.SmsTxtractParser;
import com.elvin.zoe.pojo.Conversation;
import com.elvin.zoe.template.MonthlyHtmlTemplate;
import com.elvin.zoe.util.Configurator;
import com.elvin.zoe.util.FileUtil;

/**
 * Hello world!
 *
 */
public class ParseAndConvert {

    private static Logger logger = Logger.getLogger(ParseAndConvert.class);

    public static final String ENV_IGNORE_ARCHIVE = "ignore.archvie";
    public static final String ENV_MESSAGE_START = "message.number.start";
    private boolean ignoreArchive = false;
    private int messageNumberStart = 0;

    public static void main(String[] args) throws Exception {
        System.getProperties().list(System.out);
        Configurator.init();

        ParseAndConvert parseAndConvert = new ParseAndConvert();
        parseAndConvert.init();
        parseAndConvert.run();
    }

    private void init() {
        logger.info(ENV_IGNORE_ARCHIVE + ": " + System.getProperty(ENV_IGNORE_ARCHIVE));
        String ignoreArchvieProp = System.getProperty(ENV_IGNORE_ARCHIVE);
        ignoreArchive = ignoreArchvieProp != null && ignoreArchvieProp.equalsIgnoreCase("true");

        logger.info(ENV_MESSAGE_START + ": " + System.getProperty(ENV_MESSAGE_START));
        String messageNumberStartProp = System.getProperty(ENV_MESSAGE_START);
        if (messageNumberStartProp != null)
            try {
                messageNumberStart = Integer.parseInt(messageNumberStartProp);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

	public void run() throws Exception {
        Conversation conversation = this.processFolder("/jiayuan", new JiayuanParser())
                             .merge(this.processFolder("/sms",     new SmsTxtractParser()))
                             .merge(this.processFolder("/call",    new CallLogXmlParser()))
                             .merge(this.processFolder("/msn",     new MsnParser()))
                             .merge(this.processFolder("/qq",      new QqParser()));;

        String monthlyOutPutFolder = Configurator.monthlyOutputFolder;

        Map<String, String> mapFileName2PageContent = new MonthlyHtmlTemplate(conversation).generateMonthlyHtml(messageNumberStart);

        for(Map.Entry<String, String> entry : mapFileName2PageContent.entrySet()){
            File file = new File(monthlyOutPutFolder+"/" + entry.getKey());
            logger.info(" >> " + file.getAbsolutePath());
            FileUtil.writeFile(file, entry.getValue());
        }
        logger.info("Done .");

	}

    public Conversation processFolder(String subFolderName, Parser parser) throws Exception {

        String logWorkingFoler = Configurator.logWorkingFoler;
        String logArchiveFoler = Configurator.logArchiveFoler;

        Conversation conversation = new Conversation();

        File workingFolder = new File(logWorkingFoler + subFolderName);
        if(workingFolder.exists()){
            conversation.merge(processFiles(workingFolder.listFiles(), parser));
        }

        if (ignoreArchive) {
            logger.info("Ignoring archive for " + subFolderName);
        }else{
            File archiveFoler = new File(logArchiveFoler + subFolderName);
            if (archiveFoler.exists()) {
                conversation.merge(processFiles(archiveFoler.listFiles(), parser));
            }
        }

        logger.info(parser.getClass() + " - " + conversation.getMessages().size());
        return conversation;
    }

    private Conversation processFiles(File[] files, Parser parser) throws IOException, Exception {
        Conversation conversation = new Conversation();
        for (File file : files) {
            if(file.getName().startsWith("."))continue;
            if(!file.isFile())continue;
            logger.info(file);
            String html = FileUtil.readFile(file);
            conversation.merge(parser.parseMessages(html));
        }
        return conversation;
    }



}
